import re
import logging

from google.appengine.api import urlfetch

from lib.gtwtools import gtwtools
from config import config
# To change this template, choose Tools | Templates
# and open the template in the editor.

__license__ = "GPL http://www.gnu.org/licenses/gpl.txt"
__author__="xushengs@gmail.com"
__homepage__ = "http://fdream.net"
__date__ ="2010-8-17 17:33:33"
__version = "0.1"

class OauthProxy():
    def __init__(self, username, password):
        self.username = username
        self.password = password
        
    def getTokens(self):
        params = gtwtools.get_oauth_params(base_url = config.request_token, params = {}, method = 'POST')
        oauth = gtwtools.dict2qscomma(params)
        res = urlfetch.fetch(url=config.request_token, headers={'Authorization': 'OAuth ' + oauth}, method='POST')
        if res.status_code != 200:
            logging.error('Fetch request token error.\n%s\n%s\n%s' % (res.status_code, res.headers, params))
            #handle.response.out.write('get request token failed!')
            return None

        dict = gtwtools.qs2dict(res.content)
        if dict['oauth_callback_confirmed'] != 'true':
            logging.error('Request token param error.\n%s\n%s\n%s' % (res.status_code, res.headers, params))
            #handle.response.out.write('get request token failed!')
            return None

        #memcache.set(dict['oauth_token'], dict['oauth_token_secret'], 600, namespace='TwitterRequestToken')
        #logging.error('token: %s\n%s' % (dict['oauth_token'], dict['oauth_token_secret']))
        # redirect to twitter to get authorize
        #handle.redirect('%s?oauth_token=%s' % (config.authorize, dict['oauth_token']))
        # now do it for those people who can not overcross the gfw
        # step 1:
        #    parse the authorize url and get the authenticity_token
        # step 2:
        #    post the authorize data to twitter and get oauth verifier, including these 4 items:
        #      authenticity_token
        #      oauth_token
        #      session[username_or_email]
        #      session[password]
        # step 3:
        #    parse the authorize page and get access token

        # step 1: get authenticity token
        res = urlfetch.fetch(url='%s?oauth_token=%s' % (config.authorize, dict['oauth_token']), method='GET')
        #logging.error('get authenticity token: ' + res.content)
        if res.status_code != 200:
            logging.error('Fetch authenticity token error.\n%s\n%s\n%s' % (res.status_code, res.headers, params))
            #handle.response.out.write('get authenticity token failed!')
            return None

        m = re.search('<input.*?name="authenticity_token".*?value="(.+?)"', res.content, re.MULTILINE|re.IGNORECASE)
        if m is not None:
            dict['authenticity_token'] = m.group(1)
            #logging.error('authenticity token: %s' % (dict['authenticity_token']))
        else:
            #handle.response.out.write('get authenticity token failed!')
            return None

        # step 2: post data and get oauth verifier
        post_data = 'authenticity_token=%s&oauth_token=%s&session[username_or_email]=%s&session[password]=%s' % (dict['authenticity_token'], dict['oauth_token'], self.username, self.password)
        res = urlfetch.fetch(url=config.authorize, payload=post_data, method='POST')
        if res.status_code != 200:
            logging.error('Fetch oauth verifier error.\n%s\n%s\n%s' % (res.status_code, res.headers, params))
            #handle.response.out.write('get oauth verifier failed!')
            return None

        m = re.search('<meta.*?content=".*?url=.*?oauth_verifier=(.+?)(?:&|")', res.content, re.MULTILINE|re.IGNORECASE)
        if m is not None:
            dict['oauth_verifier'] = m.group(1)
        else:
            #handle.response.out.write('get oauth verifier failed!')
            return None

        # step 3: get access token
        params = gtwtools.get_oauth_params(base_url = config.access_token, params = {'oauth_token': dict['oauth_token'], 'oauth_verifier': dict['oauth_verifier']}, token_secret = dict['oauth_token_secret'], method = 'POST')
        oauth = gtwtools.dict2qscomma(params)
        res = urlfetch.fetch(url=config.access_token, headers={'Authorization': 'OAuth ' + oauth}, method='POST')
        if res.status_code != 200:
            logging.error('Fetch access token error.\n%s\n%s\n%s' % (res.status_code, res.headers, params))
            return None

        # the right response:
        #    oauth_token=819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw&
        #    oauth_token_secret=J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA&
        #    user_id=819797&
        #    screen_name=episod
        #logging.error('Fetch access token successfull.\n%s\n%s\n%s\n%s' % (res.status_code, res.headers, params, res.content))
        return gtwtools.qs2dict(res.content)
        #handle.response.out.write('get access token success: %s, %s, %s' % (dict['oauth_token'], dict['oauth_token_secret'], dict['screen_name']))
    